// UI管理器
class UIManager {
    constructor() {
        this.currentScreen = 'mainMenu';
        this.previousScreen = null;
        this.init();
    }

    init() {
        this.bindEvents();
        this.showLoadingScreen();
        
        // 等待所有资源加载完成
        this.waitForLoad().then(() => {
            this.hideLoadingScreen();
            this.showMainMenu();
        });
    }

    async waitForLoad() {
        // 等待游戏引擎和其他系统初始化
        return new Promise((resolve) => {
            const checkLoaded = () => {
                console.log('检查系统加载状态:', {
                    gameEngine: !!window.gameEngine,
                    gameEngineLoaded: window.gameEngine?.isLoaded,
                    i18n: !!window.i18n,
                    achievementSystem: !!window.achievementSystem,
                    storyManager: !!window.storyManager
                });
                
                if (window.gameEngine && window.i18n && window.achievementSystem) {
                    console.log('✓ 所有系统已加载完成');
                    setTimeout(resolve, 500); // 额外等待500ms确保所有初始化完成
                } else {
                    setTimeout(checkLoaded, 100);
                }
            };
            checkLoaded();
        });
    }

    bindEvents() {
        // 主菜单按钮
        this.bindButton('newGameBtn', () => this.handleNewGame());
        this.bindButton('continueBtn', () => this.handleContinueGame());
        this.bindButton('achievementsBtn', () => this.showAchievements());
        this.bindButton('timelineBtn', () => this.showTimeline());
        this.bindButton('settingsBtn', () => this.showSettings());
        this.bindButton('fireworksBtn', () => this.handleFireworks());

        // 游戏UI按钮
        this.bindButton('menuBtn', () => this.handleGameMenu());
        this.bindButton('saveBtn', () => this.handleSaveGame());

        // 返回按钮（通用）
        this.bindButtons('.back-btn', () => this.showMainMenu());

        // 键盘快捷键
        this.bindKeyboardShortcuts();

        // 窗口大小改变事件
        window.addEventListener('resize', () => this.handleResize());

        // 语言切换事件
        window.addEventListener('languageChanged', () => this.updateUI());
    }

    bindButton(id, handler) {
        const element = document.getElementById(id);
        if (element) {
            element.addEventListener('click', handler);
            console.log(`✓ 绑定按钮事件: ${id}`);
        } else {
            console.error(`❌ 找不到按钮元素: ${id}`);
        }
    }

    bindButtons(selector, handler) {
        const elements = document.querySelectorAll(selector);
        elements.forEach(element => {
            element.addEventListener('click', handler);
        });
    }

    bindKeyboardShortcuts() {
        document.addEventListener('keydown', (e) => {
            // ESC键返回上一级
            if (e.key === 'Escape') {
                this.handleEscape();
            }
            
            // S键快速保存（仅在游戏中）
            if (e.key === 's' || e.key === 'S') {
                if (this.currentScreen === 'gameScreen' && (e.ctrlKey || e.metaKey)) {
                    e.preventDefault();
                    this.handleSaveGame();
                }
            }

            // 数字键选择选项（仅在游戏中）
            if (this.currentScreen === 'gameScreen' && e.key >= '1' && e.key <= '9') {
                const choiceIndex = parseInt(e.key) - 1;
                const choices = document.querySelectorAll('.choice-btn');
                if (choices[choiceIndex]) {
                    choices[choiceIndex].click();
                }
            }
        });
    }

    handleEscape() {
        switch (this.currentScreen) {
            case 'gameScreen':
                this.handleGameMenu();
                break;
            case 'achievementsScreen':
            case 'timelineScreen':
            case 'settingsScreen':
                this.showMainMenu();
                break;
            default:
                // 在主菜单，不做任何操作
                break;
        }
    }

    handleResize() {
        // 处理窗口大小改变，确保UI适配
        this.updateLayout();
    }

    updateLayout() {
        // 动态调整布局
        const vh = window.innerHeight * 0.01;
        document.documentElement.style.setProperty('--vh', `${vh}px`);
    }

    showScreen(screenId) {
        // 隐藏当前屏幕
        const currentScreenElement = document.getElementById(this.currentScreen);
        if (currentScreenElement) {
            currentScreenElement.classList.remove('active');
        }

        // 显示新屏幕
        const newScreenElement = document.getElementById(screenId);
        if (newScreenElement) {
            newScreenElement.classList.add('active');
        }

        // 更新状态
        this.previousScreen = this.currentScreen;
        this.currentScreen = screenId;

        // 触发屏幕切换事件
        window.dispatchEvent(new CustomEvent('screenChanged', {
            detail: { 
                from: this.previousScreen, 
                to: this.currentScreen 
            }
        }));
    }

    showLoadingScreen() {
        this.showScreen('loadingScreen');
    }

    hideLoadingScreen() {
        const loadingScreen = document.getElementById('loadingScreen');
        if (loadingScreen) {
            loadingScreen.classList.remove('active');
        }
    }

    showMainMenu() {
        this.showScreen('mainMenu');
        this.updateContinueButton();
    }

    showGameScreen() {
        this.showScreen('gameScreen');
    }

    showAchievements() {
        this.showScreen('achievementsScreen');
        if (window.achievementSystem) {
            window.achievementSystem.displayAchievements();
        }
    }

    showTimeline() {
        this.showScreen('timelineScreen');
        this.displayTimeline();
    }

    showSettings() {
        this.showScreen('settingsScreen');
    }

    handleFireworks() {
        // 点击烟花按钮时，直接显示烟花选择器
        if (window.fireworksSystem) {
            const fireworksBtn = document.getElementById('fireworksBtn');
            const rect = fireworksBtn.getBoundingClientRect();
            window.fireworksSystem.showFireworkSelector(rect.left, rect.bottom);
        }
    }

    handleNewGame() {
        if (window.gameEngine && window.gameEngine.hasUnsavedProgress()) {
            this.showConfirmDialog(
                window.i18n.get('confirmNewGame'),
                () => {
                    window.gameEngine.startNewGame();
                    this.showGameScreen();
                }
            );
        } else {
            window.gameEngine.startNewGame();
            this.showGameScreen();
        }
    }

    handleContinueGame() {
        if (window.gameEngine && window.gameEngine.loadGame()) {
            this.showGameScreen();
        } else {
            this.showNotification(window.i18n.get('noSaveData'));
        }
    }

    handleGameMenu() {
        this.showConfirmDialog(
            window.i18n.get('confirmExit'),
            () => this.showMainMenu()
        );
    }

    handleSaveGame() {
        if (window.gameEngine) {
            window.gameEngine.saveGame();
        }
    }

    updateContinueButton() {
        const continueBtn = document.getElementById('continueBtn');
        if (continueBtn) {
            const hasSaveData = localStorage.getItem('timeecho_save') !== null;
            continueBtn.disabled = !hasSaveData;
            continueBtn.style.opacity = hasSaveData ? '1' : '0.5';
        }
    }

    displayTimeline() {
        const timelineViz = document.getElementById('timelineVisualization');
        if (!timelineViz || !window.gameEngine) return;

        const gameState = window.gameEngine.getGameState();
        const choices = gameState.choices;
        const endings = gameState.flags.endings || [];

        timelineViz.innerHTML = '';

        // 创建时间线可视化
        const timelineContainer = document.createElement('div');
        timelineContainer.className = 'timeline-container-viz';
        timelineContainer.style.cssText = `
            position: relative;
            min-height: 300px;
            background: rgba(0, 0, 0, 0.2);
            border-radius: 8px;
            padding: 20px;
            overflow-x: auto;
        `;

        // 绘制选择路径
        if (choices.length > 0) {
            const pathElement = document.createElement('div');
            pathElement.className = 'choice-path';
            pathElement.innerHTML = '<h4>你的选择路径:</h4>';
            
            choices.forEach((choice, index) => {
                const choiceElement = document.createElement('div');
                choiceElement.className = 'choice-node';
                choiceElement.style.cssText = `
                    display: inline-block;
                    background: rgba(0, 212, 255, 0.2);
                    border: 1px solid rgba(0, 212, 255, 0.5);
                    border-radius: 20px;
                    padding: 8px 16px;
                    margin: 5px;
                    font-size: 12px;
                `;
                choiceElement.textContent = `选择 ${index + 1}`;
                pathElement.appendChild(choiceElement);
            });
            
            timelineContainer.appendChild(pathElement);
        }

        // 显示已解锁的结局
        if (endings.length > 0) {
            const endingsElement = document.createElement('div');
            endingsElement.className = 'endings-section';
            endingsElement.innerHTML = '<h4>已解锁结局:</h4>';
            endingsElement.style.marginTop = '20px';
            
            endings.forEach(ending => {
                const endingElement = document.createElement('div');
                endingElement.className = 'ending-node';
                endingElement.style.cssText = `
                    display: inline-block;
                    background: rgba(78, 205, 196, 0.2);
                    border: 1px solid rgba(78, 205, 196, 0.5);
                    border-radius: 20px;
                    padding: 8px 16px;
                    margin: 5px;
                    font-size: 12px;
                `;
                endingElement.textContent = this.getEndingName(ending);
                endingsElement.appendChild(endingElement);
            });
            
            timelineContainer.appendChild(endingsElement);
        }

        // 显示统计信息
        const statsElement = document.createElement('div');
        statsElement.className = 'stats-section';
        statsElement.innerHTML = '<h4>角色倾向:</h4>';
        statsElement.style.marginTop = '20px';
        
        const stats = gameState.stats;
        Object.keys(stats).forEach(stat => {
            if (stats[stat] > 0) {
                const statElement = document.createElement('div');
                statElement.style.cssText = `
                    margin: 5px 0;
                    padding: 5px 10px;
                    background: rgba(255, 255, 255, 0.1);
                    border-radius: 5px;
                    font-size: 14px;
                `;
                statElement.textContent = `${this.getStatName(stat)}: ${stats[stat]}`;
                statsElement.appendChild(statElement);
            }
        });
        
        timelineContainer.appendChild(statsElement);

        timelineViz.appendChild(timelineContainer);
    }

    getEndingName(endingType) {
        const endingNames = {
            scientific_hero: '科学英雄',
            explorer_pioneer: '探索先锋',
            fusion_being: '融合存在',
            quantum_observer: '量子观察者',
            safety_first: '安全第一',
            accidental_traveler: '意外旅行者'
        };
        return endingNames[endingType] || endingType;
    }

    getStatName(stat) {
        const statNames = {
            scientific: '科学理性',
            explorer: '探索精神',
            survival: '生存本能'
        };
        return statNames[stat] || stat;
    }

    showConfirmDialog(message, onConfirm, onCancel = null) {
        // 创建确认对话框
        const dialog = document.createElement('div');
        dialog.className = 'confirm-dialog';
        dialog.style.cssText = `
            position: fixed;
            top: 0;
            left: 0;
            width: 100vw;
            height: 100vh;
            background: rgba(0, 0, 0, 0.7);
            display: flex;
            align-items: center;
            justify-content: center;
            z-index: 2000;
            backdrop-filter: blur(5px);
        `;

        const dialogContent = document.createElement('div');
        dialogContent.style.cssText = `
            background: var(--bg-light);
            border: 1px solid rgba(255, 255, 255, 0.2);
            border-radius: 12px;
            padding: 30px;
            max-width: 400px;
            text-align: center;
            backdrop-filter: blur(20px);
        `;

        const messageElement = document.createElement('p');
        messageElement.textContent = message;
        messageElement.style.cssText = `
            color: var(--text-primary);
            margin-bottom: 20px;
            font-size: 16px;
            line-height: 1.5;
        `;

        const buttonContainer = document.createElement('div');
        buttonContainer.style.cssText = `
            display: flex;
            gap: 15px;
            justify-content: center;
        `;

        const confirmButton = document.createElement('button');
        confirmButton.textContent = window.i18n.get('yes');
        confirmButton.style.cssText = `
            background: var(--primary-color);
            border: none;
            color: white;
            padding: 10px 20px;
            border-radius: 6px;
            cursor: pointer;
            font-size: 14px;
            font-weight: 500;
        `;

        const cancelButton = document.createElement('button');
        cancelButton.textContent = window.i18n.get('no');
        cancelButton.style.cssText = `
            background: rgba(255, 255, 255, 0.1);
            border: 1px solid rgba(255, 255, 255, 0.2);
            color: var(--text-primary);
            padding: 10px 20px;
            border-radius: 6px;
            cursor: pointer;
            font-size: 14px;
            font-weight: 500;
        `;

        confirmButton.addEventListener('click', () => {
            document.body.removeChild(dialog);
            if (onConfirm) onConfirm();
        });

        cancelButton.addEventListener('click', () => {
            document.body.removeChild(dialog);
            if (onCancel) onCancel();
        });

        buttonContainer.appendChild(confirmButton);
        buttonContainer.appendChild(cancelButton);
        dialogContent.appendChild(messageElement);
        dialogContent.appendChild(buttonContainer);
        dialog.appendChild(dialogContent);

        document.body.appendChild(dialog);

        // ESC键取消
        const escapeHandler = (e) => {
            if (e.key === 'Escape') {
                document.body.removeChild(dialog);
                document.removeEventListener('keydown', escapeHandler);
                if (onCancel) onCancel();
            }
        };
        document.addEventListener('keydown', escapeHandler);
    }

    showNotification(message, type = 'info') {
        const notification = document.createElement('div');
        notification.className = 'ui-notification slide-in-right';
        
        const colors = {
            info: 'var(--primary-color)',
            success: 'var(--accent-color)',
            warning: 'var(--secondary-color)',
            error: '#ff4444'
        };

        notification.style.cssText = `
            position: fixed;
            top: 20px;
            right: 20px;
            background: ${colors[type]};
            color: white;
            padding: 15px 20px;
            border-radius: 8px;
            z-index: 1500;
            font-size: 14px;
            font-weight: 500;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);
            backdrop-filter: blur(10px);
        `;

        notification.textContent = message;
        document.body.appendChild(notification);

        setTimeout(() => {
            if (document.body.contains(notification)) {
                notification.style.animation = 'slideOutRight 0.3s ease-in forwards';
                setTimeout(() => {
                    if (document.body.contains(notification)) {
                        document.body.removeChild(notification);
                    }
                }, 300);
            }
        }, 3000);
    }

    updateUI() {
        // 当语言切换时更新UI文本
        window.i18n.updatePageText();
        
        // 重新加载当前屏幕的内容
        switch (this.currentScreen) {
            case 'achievementsScreen':
                if (window.achievementSystem) {
                    window.achievementSystem.displayAchievements();
                }
                break;
            case 'timelineScreen':
                this.displayTimeline();
                break;
        }
    }

    getCurrentScreen() {
        return this.currentScreen;
    }

    // 添加CSS动画样式
    addAnimationStyles() {
        const style = document.createElement('style');
        style.textContent = `
            @keyframes slideOutRight {
                from { transform: translateX(0); opacity: 1; }
                to { transform: translateX(100%); opacity: 0; }
            }
        `;
        document.head.appendChild(style);
    }
    
    getCurrentScreen() {
        return this.currentScreen;
    }
    
    updateUI() {
        // 更新UI文本
        if (window.i18n) {
            window.i18n.updatePageText();
        }
    }
}

// 创建全局UI管理器实例
window.uiManager = new UIManager();